package com.share.common.utils;

import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class PageUtil {

    /**
     * 内存分页
     *
     * @param list
     * @param pageNum  页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public static <T> List<T> startPage(List<T> list, int pageNum, int pageSize) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }

        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引

        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        return list.subList(fromIndex, toIndex);
    }


    //获取所有分页的角标
    public static List<Integer[]> listPageIndex(int collectionSize, int pageSize) {
        List<Integer[]> reList = new LinkedList<>();
        if (collectionSize == 0) {
            return reList;
        }

        if (pageSize < 1) {
            throw new RuntimeException("pageSize参数错误");
        }

        Integer count = collectionSize; // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        //分页角标获取
        for (int i = 0; i < pageCount; i++) {
            int startIndex = i * pageSize; // 开始索引
            int endIndex = startIndex + pageSize; // 结束索引
            if ((i + pageSize) > count) {
                endIndex = count;
            }
            reList.add(new Integer[]{startIndex, endIndex});
        }
        return reList;
    }

    public static void main(String[] args) {
        List<Integer[]> list = listPageIndex(8, 1);
        list.forEach(e -> System.out.println(e[0] + "-" + e[1]));
    }
}
